package com.red.controller;


import com.red.pojo.Page;
import com.red.pojo.Result;
import com.red.pojo.entity.Order;
import com.red.pojo.model.LoginUser;
import com.red.service.IOrderService;
import com.red.util.HttpStatusUtil;
import com.red.util.JWTUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private IOrderService orderService;

    /**
     * 插入订单
     *
     * @param order 订单信息
     * @return 插入结果
     */
    @PostMapping
    public Result add(Order order, HttpServletRequest request) {
//        if (order.getHouseId() == 0 || order.getUserId() == 0) {
//            return Result.error("缺少必要参数");
//        }

//        return orderService.insertOrder(order) > 0 ? Result.success() : Result.error();
        return Result.error();
    }

    /**
     * 删除订单
     *
     * @param orderId 订单ID
     * @return 删除结果
     */
    @DeleteMapping
    public Result delete(@RequestParam int orderId) {
        return orderService.deleteOrderByID(orderId) > 0 ? Result.success() : Result.error();
    }


    /**
     * 更新订单
     *
     * @param order 更新订单信息
     * @return 更新结果
     */
    @PutMapping
    public Result update(Order order) {
        return orderService.updateOrder(order) > 0 ? Result.success() : Result.error();
    }

    /**
     * 带条件查询所有订单
     *
     * @param order 条件
     * @param page  页数
     * @param size  长度
     * @return 订单集和分页信息
     */
    @GetMapping("/{page}/{size}")
    public Result list(Order order, @PathVariable int page, @PathVariable int size) {
        ArrayList<Object> payload = new ArrayList<>();
        Page page1 = new Page(orderService.selectOrderCount(order), page, size);
        List<Order> orders = orderService.selectOrderList(order, page1.getCurrent(), page1.getSize());
        payload.add(orders);
        payload.add(page1);

        return new Result(HttpStatusUtil.SUCCESS, "获取成功", payload);
    }

    @GetMapping("/")
    public Result myOrder(HttpServletRequest request) {
        LoginUser loginUser = JWTUtil.getLoginUser(request);
        return orderService.selectOrderListV2(loginUser.getUserID());
    }

    @PostMapping("/pay/{orderId}")
    public Result payOrder(@PathVariable int orderId, HttpServletRequest request) {
        LoginUser loginUser = JWTUtil.getLoginUser(request);
        return orderService.payOrder(loginUser.getUserID(), orderId);
    }
}
